import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

import { fetchUserInfo } from '@/api/user'

export const useVideoStore = defineStore('video', () => {
  const chapterTotal = ref(0)
  const hasPreview = ref(false)
  const likeCount = ref(0)
  const playCount = ref(0)
  const collectCount = ref(0)
  const isLike = ref(false)
  const isCollect = ref(false)

  const activeIndexInSwiper = ref(0)
  const playChapter = computed(() => activeIndexInSwiper.value + 1)

  const prevTeleplayId = ref(0) // 上一个电视剧id

  return {
    chapterTotal,
    hasPreview,
    likeCount,
    playCount,
    collectCount,
    isLike,
    isCollect,

    activeIndexInSwiper,
    playChapter,

    prevTeleplayId
  }
})

export const useUserStore = defineStore('user', () => {
  const userToken = ref()
  const nickname = ref('')
  const email = ref(undefined)
  const portraitUrl = ref('') // 头像地址
  const uuid = ref('')
  const signInday = ref(0) // 用户签到天数
  const loginType = ref(3) // 1 google 登录， 2 facebook 登录, 3 device 登录
  const cash = ref(0)
  const coin = ref(0)
  const eggCount = ref(0)
  const eggCountTotal = ref(0)
  const turntableCount = ref(0)
  const turntableCountTotal = ref(0)
  const finishNewbieTask = ref(false)
  const firstSign = ref(false)
  const signInState = ref(false) // 今日签到状态
  const loading = ref(false) // 用来判断是否加载过登录接口
  const receiveReward = ref(false) // 是否领取过新手任务奖励

  const loginStatus = computed(() => {
    return userToken.value && email.value.length > 0
  })

  async function handleGetUserInfo() {
    const res = await fetchUserInfo({ device: uuid.value })
    const userInfo = res.data.data
    nickname.value = userInfo.nickName
    email.value = userInfo.email
    portraitUrl.value = userInfo.userImage
    cash.value = userInfo.cashAmount
    coin.value = userInfo.coinAmount
    eggCount.value = userInfo.eggCount
    turntableCount.value = userInfo.turntableCount
    uuid.value = userInfo.device
    finishNewbieTask.value = userInfo.finishNewbieTask
    firstSign.value = userInfo.firstSign
    receiveReward.value = userInfo.receiveReward
    if (loading.value) {
      loading.value = false
    }
  }

  function generateUUID() {
    if (uuid.value.length === 0) {
      let array = new Uint32Array(2);
      window.crypto.getRandomValues(array);
      uuid.value = btoa(Array.from(array).join());
    }
  }

  return {
    // state
    nickname,
    email,
    portraitUrl,
    userToken,
    uuid,
    signInday,
    loginType,
    cash,
    coin,
    eggCount,
    turntableCount,
    finishNewbieTask,
    receiveReward,
    firstSign,
    signInState,
    loading,
    eggCountTotal,
    turntableCountTotal,

    // getter
    loginStatus,

    // function
    handleGetUserInfo,
    generateUUID
  }

}, { persist: true })